package p_304

import java.io.*
import java.net.Socket
import java.net.URLConnection
import java.util.*
import java.util.logging.Logger

class RequestProcessor(private var rootDir: File,
                       private val connection: Socket,
                       private val fileName: String = "index.html") : Runnable {

    private val logger = Logger.getLogger("RequestProcessor")

    init {
        if (rootDir.isFile) throw IllegalArgumentException("rootDir 不能是文件")
        rootDir = rootDir.canonicalFile
    }

    override fun run() {
        val rootPath = rootDir.path
        try {
            val raw = BufferedOutputStream(connection.getOutputStream())
            val writer = OutputStreamWriter(raw)
            val inReader: Reader = InputStreamReader(BufferedInputStream(connection.getInputStream()))
            val requestLine = StringBuilder()

            while (true) {
                val c = inReader.read()
                if (c == -1 || c.toChar() == '\r' || c.toChar() == '\n') break
                requestLine.append(c.toChar())
            }
            val get = requestLine.toString()
            logger.info("${connection.remoteSocketAddress} -->$get")
            val tokens: List<String> = get.split("\\s+")
            val method = tokens[0]
            var version = ""

            if ("GET".equals(method)) {
                var fName = tokens[1]
                if (fName.endsWith("/")) fName += fileName
                val contentType = URLConnection.getFileNameMap().getContentTypeFor(fName)
                if (tokens.size > 2) version = tokens[2]
                val theFile = File(rootDir, fName.substring(1, fName.length))
                if (theFile.canRead() && theFile.canonicalPath.startsWith(rootDir.absolutePath)) {
                    val bytes = theFile.readBytes()
                    if (version.startsWith("http")) {
                        sendHeader(writer, "HTTP/1.0 200 OK", contentType, bytes.size)
                    }
                    writer.write(bytes.toString())
                    writer.flush()
                } else { // 找不到文件
                    val body = StringBuilder().append("<HTML>\r\n")
                            .append("<HEAD>")
                            .append("404 File Not Found !")
                            .append("<HEAD>")
                            .append("<BODY>")
                            .append(" HTTP ERROR 404 : File Not Found")
                            .append("<BODY>")
                            .append("<HTML>").toString()

                    writer.write(body)
                    writer.flush()
                }


            } else { // 不是GET
                val body = StringBuilder().append("<HTML>\r\n")
                        .append("<HEAD>")
                        .append("ONLY GET ")
                        .append("<HEAD>")
                        .append("<BODY>")
                        .append("ONLY GET")
                        .append("<BODY>")
                        .append("<HTML>").toString()

                writer.write(body)
                writer.flush()
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    private fun sendHeader(writer: OutputStreamWriter, responseCode: String, contentType: String?, size: Int) {
        writer.write("$responseCode\r\n")
        writer.write("Date:${Date()}\r\n")
        writer.write("Server:JHttp 2.0 \r\n")
        writer.write("Content-length：$size")
        writer.write("Conent-type: $contentType")
        writer.flush()
    }

}